<template>
  <el-drawer v-model="_isOpen" size="1160" class="marque_select_drawer">
    <template #header>
      <div class="title">商品规格选择</div>
    </template>

    <template #default>
      <div class="content">
        <div class="content_head">
          <div class="product_info">
            <div class="info_img">
              <img :src="productInfo.mainPicUrl" />
            </div>
            <div class="info_detail">
              <div class="detail_title">{{ productInfo.productAliasName }}</div>
              <div class="detail_price" v-if="isHidePrice === 1">
                <span class="price_tag">{{ selectPrice.priceType }}</span>
                <span class="price_text">{{ `¥${selectPrice.num}` }}</span>
              </div>
              <div class="detail_info mt10">
                <span>上市时间：{{ productInfo.appearTime }}</span>
                <span>已售：{{ productInfo.businessShowSaleNum }}</span>
                <span>商品ID：{{ productInfo.productId }}</span>
                <span>商品等级：--</span>
              </div>
            </div>
          </div>
        </div>
        <div class="split_box" />
        <div class="content_detail">
          <div class="detail_box" v-if="productInfo.productPrizeInfo">
            <div class="box_title">商品附加消息</div>
            <div class="message_text">{{ productInfo.productPrizeInfo }}</div>
          </div>
          <div v-if="showremark">
            <template v-for="(item, index) in productInfo.specificationList" :key="item.id">
              <div class="detail_box">
                <div class="box_title">{{ item.specificationName }}</div>
                <div class="box_content">
                  <template v-for="temp in item.children" :key="temp.id">
                    <div
                      v-if="item.speType === specType.TEXT_TYPE"
                      :class="`box_item ${isActive(temp, index)}`"
                      @click="handleClickSetSku(temp, index)"
                    >
                      <div class="text_item">
                        {{ temp.specificationVal }}
                      </div>
                    </div>
                    <div v-else @click="handleClickSetSku(temp, index)" :class="`box_item ${isActive(temp, index)}`">
                      <el-tooltip :content="temp.specificationVal" placement="bottom" effect="light">
                        <div
                          class="color_item"
                          v-if="item.speType === specType.COLOR_TYPE"
                          :style="{ 'background-color': temp.statsText }"
                        />
                        <img v-else class="color_item" :src="temp.statsText" :alt="temp.specificationVal" />
                      </el-tooltip>
                    </div>
                  </template>
                </div>
              </div>
            </template>
          </div>

          <div class="detail_box">
            <shopRemark v-model="remark" />
          </div>
        </div>
      </div>
    </template>

    <template #footer>
      <div class="footer">
        <el-button style="background: #f2f3f5; color: #424e66; border: 0" @click="cancel()">取消</el-button>
        <el-button style="background: #424e66; border: 0" type="primary" :disabled="!checkIsAllow()" @click="submit()">
          确认
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { getShopDetail } from "@/apis/shopHome/detail";
import { getCustomerRemark } from "@/apis/quote-price/following";
import shopRemark from "@/views/home/components/shopRemark.vue";
import { ElMessage } from "element-plus";

const specType = { TEXT_TYPE: 1, COLOR_TYPE: 2, IMAGE_TYPE: 3 };

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  product: { type: Object, default: () => ({}) },
  showremark: { type: Boolean, default: true },
  _time: { type: Number, default: null },
  isHidePrice: { type: Boolean, default: true }
});

const _isOpen = computed({
  get: () => props.modelValue,
  set: newVal => emits("update:modelValue", newVal)
});
const emits = defineEmits(["update:modelValue", "confirm"]);

const productInfo = ref({});
const selectList = ref([]);
const selectPrice = ref({});
const businessSkuId = ref("");
const remark = ref("");

/**
 * 校验选中的sku采购价是否在商品分类的价格限制区间内。
 */
const checkIsAllow = () => {
  const _prodObj = JSON.parse(JSON.stringify(props.product));
  let rangeFlag = true; //是否在价格限制区间内
  if (
    Number(_skuObj.value?.factoryRealPrice) >= Number(_prodObj?.costPriceMin) &&
    Number(_skuObj.value?.factoryRealPrice) <= Number(_prodObj?.costPriceMax)
  ) {
    rangeFlag = true; //在范围内
  } else {
    rangeFlag = false; //不在范围内
  }
  // console.log("点击的商品===", rangeFlag, _skuObj.value?.factoryRealPrice, _prodObj?.costPriceMin, _prodObj?.costPriceMax);
  return rangeFlag;
};

const getremark = async () => {
  const { code, msg } = await getCustomerRemark({ businessSkuId: props.product.businessSkuId, code: props._time });
  code === 200 && (remark.value = msg);
};
const getDeatil = async () => {
  if (props.product.businessSkuId) {
    getremark();
  }
  let postData = new FormData();
  postData.append("productId", props.product.id);
  const { code, data } = await getShopDetail(postData);
  code === 200 && (productInfo.value = data);
  businessSkuId.value = props.product.businessSkuId || "";
  setSelectVal(productInfo.value, businessSkuId.value);
};

const handleClickSetSku = (item, index) => {
  selectList.value[index] = item.specificationVal;
  setSelectVal(productInfo.value);
};

const _skuObj = ref({});
const setSelectVal = (item, skuId) => {
  let skuObj;
  if (skuId) {
    skuObj = item.skuList.find(item => skuId === item.id);
    _skuObj.value = skuObj;
    selectList.value = JSON.parse(skuObj.properties).map(item => item.specificationVal);
  } else {
    if (selectList.value.length === 0) {
      selectList.value = item.specificationList.map(item => item.children[0].specificationVal);
    }

    let selectStr = selectList.value.join("");
    let skuStrList = item.skuList.map(item => {
      let skuStr = JSON.parse(item.properties).reduce((pre, cur) => {
        return pre + cur.specificationVal;
      }, "");
      return { skuStr, ...item };
    });
    skuObj = skuStrList.find(item => item.skuStr === selectStr);
    businessSkuId.value = skuObj.id;
    _skuObj.value = skuObj;

    const rangeFlag = checkIsAllow();
    if (!rangeFlag) {
      ElMessage({
        message: "温馨提示，当前所选商品，均不在设置可选商品范围内，请重新选择后确认~~",
        type: "error",
        grouping: true,
        duration: 1000
      });
    }
  }
  setSelectPrice(skuObj);
};

const setSelectPrice = item => {
  if (item.clinetRealPrice === item.clinetPrice) selectPrice.value.priceType = "正价";
  else selectPrice.value.priceType = "特价";

  selectPrice.value.num = item.clinetRealPrice;
};

const isActive = (item, index) => {
  if (item.specificationVal === selectList.value[index]) {
    return "item_active";
  }
  return "";
};

const cancel = () => {
  _isOpen.value = false;
};

const submit = () => {
  console.log("skuId=====>", businessSkuId.value);
  console.log("remark=====>", remark.value);
  emits("confirm", businessSkuId.value, remark.value, _skuObj.value);
};

(() => {
  console.log("open");
  getDeatil();
})();
</script>
<style lang="scss">
.marque_select_drawer {
  .title {
    color: #131414;
    font-size: 18px;
  }
  .content {
    height: 100%;
    .content_head {
      margin-bottom: 20px;
      .product_info {
        padding-top: 5px;
        display: flex;
        .info_img {
          img {
            border-radius: 4px;
            width: 150px;
            height: 150px;
          }
        }
        .info_detail {
          flex: 1;
          padding: 15px 20px 0;
          .detail_title {
            font-size: 18px;
            color: #3d3d3d;
            width: 400px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            font-weight: 700;
          }
          .detail_price {
            display: flex;
            gap: 20px;
            padding: 34px 0;
            .price_tag {
              color: #ff8928;
              border: 1px solid #ff8928;
              font-size: 16px;
              line-height: 24px;
              padding: 0 13px;
            }
            .price_text {
              font-size: 24px;
              font-weight: 700;
              color: #ff3333;
            }
          }
          .detail_info {
            display: flex;
            gap: 50px;
            color: #86909c;
            font-size: 12px;
          }
        }
      }
    }
    .split_box {
      width: calc(100% + 40px);
      background: #eef1f4;
      height: 10px;
      position: relative;
      right: 20px;
    }
    .content_detail {
      padding: 10px 0;
      height: calc(100% - 200px);
      overflow: auto;
      .detail_box {
        .box_title {
          color: #86909c;
          font-size: 18px;
          padding: 10px 0;
        }
        .box_content {
          display: flex;
          flex-wrap: wrap;
          gap: 10px 20px;
          margin-bottom: 10px;
          .box_item {
            border-radius: 3px;
            .text_item {
              font-size: 14px;
              line-height: 24px;
              padding: 7px 24px;
              border: 1px solid #dcdfe6;
              border-radius: 3px;
              box-sizing: border-box;
            }
            .color_item {
              box-sizing: border-box;
              border-radius: 3px;
              border: 1px solid #dcdfe6;
              width: 90px;
              height: 90px;
            }
          }
          .item_active {
            outline: 2px solid #ff8928;
            outline-offset: -2px;
          }
          .box_item:hover {
            outline: 2px solid #ff8928;
            outline-offset: -2px;
          }
        }
        .message_text {
          background: #f5f7fa;
          color: #3d3d3d;
          line-height: 24px;
          padding: 10px;
        }
      }
    }
  }
  .footer {
    box-sizing: border-box;
    width: 100%;
    display: flex;
    justify-content: center;
    .el-button {
      width: 108px;
      height: 36px;
    }
  }
  .el-drawer__header {
    margin-bottom: 0px !important;
  }
}
</style>
